package cn.edu.jxust.core.infrastructure.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * MyBatisPlus 在插入更新时自动填充 create update 等字段
 * @author liuguangyun
 * @since 2020-07-01
 */

@Slf4j
@Component
public class MyBatisPlusHandler implements MetaObjectHandler {

    /**
     * 插入数据记录时
     * @param metaObject 数据元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {

//        log.info("[MyBatisPlusHandler]: start insert fill");
        this.setFieldValByName("createDate", LocalDate.now(),metaObject);
        this.setFieldValByName("updateDate", LocalDate.now(),metaObject);
        this.setFieldValByName("createTime", LocalTime.now(),metaObject);
        if(this.getFieldValByName("createDatetime", metaObject) == null){
            this.setFieldValByName("createDatetime", LocalDateTime.now(),metaObject);
        }
        this.setFieldValByName("updateDatetime", LocalDateTime.now(),metaObject);

    }

    /**
     * 插入或者更新数据记录时
     * @param metaObject 数据元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {

//        log.info("[MyBatisPlusHandler]: start update fill");
        this.setFieldValByName("updateDate", LocalDate.now(),metaObject);
        this.setFieldValByName("updateDatetime", LocalDateTime.now(),metaObject);

    }
}
